package com.xin.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;

/**
 * @author WYX
 * @create 2020-04-05-21:55
 */
/*采用file.Transto来保存上传的文件*/
@RestController
public class FileController {

    @RequestMapping("/upload2")
    public String fileUpload2(@RequestParam("file") CommonsMultipartFile file,HttpServletRequest request) throws IOException {

        //上传路径保存设置
        String path = request.getServletContext().getRealPath("/upload");
        File realPath=new File(path);
        if(!realPath.exists()){
            realPath.mkdir();
        }

        //上传文件地址
        System.out.println("上传文件保存地址："+realPath);

        //通过CommonsMultipartFile的方法直接写文件（）
        file.transferTo(new File(realPath+"/"+file.getOriginalFilename()));

        return "redirect:/index.jsp";
    }

    @RequestMapping(value = "/download")
    public String download(HttpServletRequest request, HttpServletResponse response) throws IOException {

        //要下载的图片地址
        String path=request.getServletContext().getRealPath("/upload");
        String fileName="基础语法.jsp";

        //1、设置response响应头
        response.reset();//设置页面不缓存，清空buffer
        response.setCharacterEncoding("utf-8");//字符编码
        response.setContentType("multipart/form-data");//二进制传输数据
        //设置响应头
        response.setHeader("Content-Disposition","attachment;fileName="+ URLEncoder.encode(fileName,"utf-8"));

        File file=new File(path,fileName);

        //2、读取文件--输入流
        InputStream inputStream=new FileInputStream(file);
        //3、写出文件--输出流
        OutputStream outputStream=response.getOutputStream();


        byte[] buff=new byte[1024];
        int index=0;

        //4、执行 写出操作
        while((index=inputStream.read(buff))!=-1){
            outputStream.write(buff,0,index);
            outputStream.flush();
        }
        outputStream.close();
        inputStream.close();

        return null;
    }
}
